<template>
  <div class="AddOrUpdate_main add_container column_two">
    <div ref="scrollRef" class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="展示编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="展示名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="统计设置" name="first">
            <div ref="table_container" class="table_container draggableTable addRow_table">
              <el-table
                ref="table"
                :data="tableData"
                stripe
                border
                row-key="id"
                style="width: 99.9%"
                :cell-class-name="cellClassName"
                :row-class-name="rowClassName"
                @selection-change="selectionChange1"
              >
                <el-table-column label="显示" width="100">
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.isShow"
                      active-value="1"
                      inactive-value="0"
                      active-color="#13ce66"
                      inactive-color="#999999"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="name"
                  align="center"
                  label="名称"
                >
                  <template slot-scope="scope">
                    <div style="text-align:center">{{ scope.row.name }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="排序" width="100">
                  <template>
                    <div>
                      <svg-icon style="height:25px;width:25px" icon-class="drag2" />
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane label="图表设置" name="second">
            <div ref="table_container" class="table_container draggableTable2 addRow_table">
              <el-table
                ref="table2"
                :data="tableData2"
                stripe
                border
                row-key="id"
                style="width: 99.9%"
                :cell-class-name="cellClassName"
                :row-class-name="rowClassName2"
                @selection-change="selectionChange1"
              >
                <el-table-column label="显示" width="180">
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.isShow"
                      active-value="1"
                      inactive-value="0"
                      active-color="#13ce66"
                      inactive-color="#999999"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="name"
                  label="名称"
                  align="center"
                >
                  <template slot-scope="scope">
                    <div style="text-align:center">{{ scope.row.name }}</div>
                  </template>
                </el-table-column>
                <el-table-column
                  label="自定义配置"
                  align="center"
                  min-width="200"
                >
                  <template slot-scope="scope">
                    <div v-if="'number' in scope.row" class="customization">
                      <div class="customization_name">
                        目标值：
                      </div>
                      <div class="customization_value">
                        <el-input
                          v-model="scope.row.number"
                          placeholder="请输入"
                          type="number"
                          @input="haveTwoDecimalPlaces($event,scope.$index)"
                        />
                      </div>
                    </div>
                    <div v-if="'threshold' in scope.row" class="customization">
                      <div class="customization_name">
                        阈值：
                      </div>
                      <div class="customization_value">
                        <el-input
                          v-model="scope.row.threshold"
                          placeholder="请输入"
                          type="number"
                        />
                      </div>
                    </div>
                    <div v-if="'deviceIds' in scope.row" class="customization">
                      <div class="customization_name">
                        设备：
                      </div>
                      <div class="customization_value">
                        <el-select
                          v-model="scope.row.deviceIds"
                          multiple
                          collapse-tags
                          multiple-limit="4"
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="item in deviceOptions"
                            :key="item.companyDeviceId"
                            :label="item.deviceName"
                            :value="item.companyDeviceId"
                          />
                        </el-select>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="排序" width="100">
                  <template>
                    <div>
                      <svg-icon style="height:25px;width:25px" icon-class="drag2" />
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo } from '@/api/system/largeScreenDetail'
import Sortable from 'sortablejs'
import { mapGetters } from 'vuex'
import { realStatusList as getDeviceOptions } from '@/api/superManage/iotManage/iotConfiguration'
export default {
  name: 'AddOrUpdate',
  computed: {
    ...mapGetters([
      'companyId'
    ])
  },
  props: {
    layerid: {},
    id: {}
  },
  data() {
    return {
      formData: {
        id: '',
        code: '',
        name: '',
        remark: ''
      },
      pageData: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      activeName: 'first',
      rules: {
        code: [
          { required: true, message: '展示编码不能为空', trigger: 'change' }
        ],
        name: [
          { required: true, message: '展示名称不能为空', trigger: 'change' }
        ]
      },
      tableHeight: '340',
      selectionsAll1: [],
      deviceOptions: [],
      tableData: [
      // 可选的统计数据项
        {
          name: '设备总数',
          icon: '设备总数',
          dataKey: 'deviceTotalNumber',
          bgColor: '#FF9292',
          isShow: '1'
        },
        {
          name: '今日点检（含待点检）',
          icon: '今日待点检',
          dataKey: 'waitCheckNumber',
          bgColor: '#FF9ADC',
          isShow: '1'
        },
        {
          name: '本月待保养',
          icon: '本月待保养',
          dataKey: 'waitMaintainNumber',
          bgColor: '#D7B0FF',
          isShow: '1'
        },
        {
          name: '维修中设备数',
          icon: '维修中设备数',
          dataKey: 'repairNumber',
          bgColor: '#FFCA74',
          isShow: '1'
        },
        {
          name: '安全库存报警',
          icon: '安全库存报警',
          dataKey: 'safetyStockAlarm',
          bgColor: '#CFFF79',
          isShow: '1'
        },
        {
          name: '今日点检逾期数',
          icon: '今日点检超期数',
          dataKey: 'overdueCheckNumber',
          bgColor: '#60B5FF',
          isShow: '1'
        },
        {
          name: '备件待盘点工单',
          icon: '待盘点工单',
          dataKey: 'waitSpareCheckNumber',
          bgColor: '#78FFBB',
          isShow: '1'
        },
        {
          name: '维修工单',
          icon: '维修中工单',
          dataKey: 'repairRecordNumber',
          bgColor: '#76FFFE',
          isShow: '1'
        }
      ],
      tableData2: [
        { isShow: '1', name: '报警信息', component: 'AlarmInformation' },
        { isShow: '1', name: '产能统计', component: 'CapacityStatistics', number: 100 },
        { isShow: '1', name: '点检计划完成率', component: 'checkPlanFinishedRate' },
        { isShow: '1', name: '今日点检明细', component: 'DetailInspectedToday' },
        { isShow: '1', name: '本月待保养明细', component: 'DetailsMaintainMonth' },
        { isShow: '1', name: '设备状态统计', component: 'EquipmentStatusTodays' },
        // { isShow: '0', name: '设备利用率', component: 'EquipmentUtilization' },
        { isShow: '0', name: 'OEE时序图', component: 'OEESequenceDiagram', number: 100 },
        // { isShow: '0', name: '在岗人员', component: 'OnDutyPersonnel' },
        // { isShow: '0', name: '故障次数排行', component: 'RankingFaultTimes' },
        // { isShow: '0', name: '车间设备实时统计', component: 'WorkshopEquipmentRealTime' },
        { isShow: '0', name: '已逾期工单', component: 'OverdueWorkOrder' },
        { isShow: '0', name: '维修工单明细', component: 'WorkOrderDetailsInRepair' },
        { isShow: '0', name: '设备紧急程度分布', component: 'DegreeDistribution' },
        // { isShow: '0', name: '点检计划完成率', component: 'CheckPlanCompletedRatio' },
        { isShow: '0', name: '维修费用统计', component: 'MaintenanceCostStatistics' },
        { isShow: '0', name: '备件消耗排行', component: 'SparePartsConsumptionRanking' },
        { isShow: '0', name: '设备位置分布', component: 'LocationDistribution' },
        { isShow: '0', name: '保养计划及时率', component: 'MaintainPlanTimelinessRate' },
        { isShow: '0', name: '任务统计', component: 'TaskStatistics', length: '2' },

        { isShow: '0', name: '设备功率', component: 'EquipmentPower', deviceIds: '' },
        { isShow: '0', name: '峰平谷电量', component: 'PowerDistribution' },
        { isShow: '0', name: '电量同比分析', component: 'ElectricityYearOnYear' },
        { isShow: '0', name: '今日设备状态', component: 'EquipmentStatusStatistic', deviceIds: '' },
        { isShow: '0', name: '日用电量趋势', component: 'DailyElectricity', threshold: 0 }
      ]
    }
  },
  mounted() {
    this.pageData.customerId = this.companyId
    this.$nextTick(() => {
      this.rowDrop()
      this.rowDrop2()
    })
    this.getDeviceOptions()
    if (!this.id) { // 没有id就是新增
      Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  methods: {
    getDeviceOptions() {
      getDeviceOptions(this.pageData).then(res => {
        this.deviceOptions = res.data
      })
    },
    // 保留两位小数
    haveTwoDecimalPlaces(e, index) {
      if (e.indexOf('.') > -1) {
        const afterPoint = e.split('.')
        if (e !== 0 && afterPoint[1].length > 2) {
          this.tableData2[index].number = e.slice(0, e.indexOf('.') + 3)
          this.$message.warning('至多可输入两位小数')
        } else if (e == 0) {
          this.tableData2[index].number = 0
        }
      } else {
        this.tableData2[index].number = e
      }
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.tableData = JSON.parse(res.data.statistical)
        this.tableData2 = JSON.parse(res.data.chart)
      })
    },
    handleClick() {
      console.log(this.activeName)
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    // 表格拖动排序
    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.draggableTable')
        .querySelector('.el-table__body-wrapper').querySelector('tbody')
      const _this = this
      Sortable.create(tbody, {
        draggable: '.normalRow',
        filter: '.el-input__inner', // Selectors that do not lead to dragging (String or Function)
        preventOnFilter: false, // Call `event.preventDefault()` when triggered `filter`
        onEnd({ newIndex, oldIndex }) {
          const cacheData1 = _this.$deepClone(_this.tableData[oldIndex])
          const cacheTableData = _this.$deepClone(_this.tableData)
          cacheTableData.splice(oldIndex, 1)
          cacheTableData.splice(newIndex, 0, cacheData1)
          _this.tableData = []
          const cacheScroll = _this.$refs.scrollRef.scrollTop
          setTimeout(() => { // 加延时重置表格
            _this.tableData = cacheTableData
            setTimeout(() => {
              _this.$refs.scrollRef.scrollTop = cacheScroll
            }, 1)
          }, 1)
        }
      })
    },
    rowDrop2() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.draggableTable2')
        .querySelector('.el-table__body-wrapper').querySelector('tbody')
      console.log(tbody)
      const _this = this
      Sortable.create(tbody, {
        draggable: '.normalRow2',
        filter: '.el-input__inner', // Selectors that do not lead to dragging (String or Function)
        preventOnFilter: false, // Call `event.preventDefault()` when triggered `filter`
        onEnd({ newIndex, oldIndex }) {
          const cacheData1 = _this.$deepClone(_this.tableData2[oldIndex])
          const cacheTableData = _this.$deepClone(_this.tableData2)
          cacheTableData.splice(oldIndex, 1)
          cacheTableData.splice(newIndex, 0, cacheData1)
          _this.tableData2 = []
          const cacheScroll = _this.$refs.scrollRef.scrollTop
          setTimeout(() => { // 加延时重置表格
            _this.tableData2 = cacheTableData
            setTimeout(() => {
              _this.$refs.scrollRef.scrollTop = cacheScroll
            }, 1)
          }, 1)
        }
      })
    },
    cellClassName(data) {
      if (data.column.property == 'operate') {
        if (data.rowIndex % 2 == 0) { // 单数行
          return 'fixed one'
        } else { // 双数行
          return 'fixed two'
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.tableData.length) {
        return 'addRow'
      } else {
        return 'normalRow'
      }
    },
    rowClassName2({ row, rowIndex }) {
      if (rowIndex == this.tableData2.length) {
        return 'addRow2'
      } else {
        return 'normalRow2'
      }
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          var statisticalData = []
          var chartData = []
          var chartHasNumberData = []
          if (this.tableData.length > 0) {
            statisticalData = JSON.stringify(this.tableData)
          } else {
            statisticalData = JSON.stringify(this.tableData)
          }
          if (this.tableData2.length > 0) {
            chartData = JSON.stringify(this.tableData2)
            chartHasNumberData = this.tableData2
          } else {
            chartData = JSON.stringify(this.tableData2)
            chartHasNumberData = this.tableData2
          }
          if (chartHasNumberData.some(item => 'number' in item == true && !item.number)) {
            this.$message.warning('图标设置中存在目标值未填写的数据')
            return false
          } else if (chartHasNumberData.filter(item => item.length && item.isShow == '1').length > 0 && chartHasNumberData.filter(item => !item.length && item.isShow == '1').length > 4) {
            this.$message.warning('选择完任务统计后,最多只可选择4项图例')
            return false
          } else if (chartHasNumberData.filter(item => item.length && item.isShow == '1').length == 0 && chartHasNumberData.filter(item => !item.length && item.isShow == '1').length > 6) {
            this.$message.warning('最多只可选择6项图例')
            return false
          } else {
            addOrUpdate({ ...this.formData, statistical: statisticalData, chart: chartData }).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.getList() // 调用父组件的刷新方法
            })
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
  .customization{
    display: flex;
    .customization_name{
      width: 100px;padding-right: 10px;
      display: flex;align-items: center;justify-content: flex-end;
    }
    .customization_value{
      flex: 1;
      display: flex;align-items: center;
    }
  }

</style>
